import pgzrun
from vec import *
import time
import random

WIDTH = 600
HEIGHT = 440

BACK_COLOR = (0, 0, 0)
PEN_COLOR = (0, 200, 0)

wastime = time.time()
betweentime = 0
sumtime = 0

class PointTail:
    def __init__(self):
        self.tail = []
        self.sumtime = 0.0

    def UpdatePoint(self, x, y):
        for i in range(self.count - 2, -1, -1):
            self.tail[i + 1].x = self.tail[i].x
            self.tail[i + 1].y = self.tail[i].y
        self.tail[0].x = x
        self.tail[0].y = y

    def InitPoints(self, n):
        self.count = n
        self.vx = random.randint(-5, 5)
        self.vy = random.randint(-5, 5)
        px = random.randint(0, WIDTH - 1)
        py = random.randint(0, HEIGHT - 1)
        for i in range(self.count):
            self.tail.append(Vec2(px, py))

    def GetPoint(self, index):
        return self.tail[index]

    def Update(self):
        global betweentime
        newX = self.tail[0].x + self.vx
        newY = self.tail[0].y + self.vy

        if newX >= WIDTH - 1:
            newX = WIDTH - 1
            self.vx *= -1
        elif newX <= 0:
            newX = 0
            self.vx *= -1

        if newY >= HEIGHT - 1:
            newY = HEIGHT - 1
            self.vy *= -1
        elif newY <= 0:
            newY = 0
            self.vy *= -1

        self.sumtime += betweentime

        if self.sumtime > 0.1: 
            self.UpdatePoint(newX, newY)
            self.sumtime = 0.0
        else:
            self.tail[0].x = newX
            self.tail[0].y = newY

pointCount = 4
p = []
for i in range(pointCount):
    pt = PointTail()
    pt.InitPoints(4)
    p.append(pt)

def update():
    global betweentime, wastime
    nowtime = time.time()
    betweentime = nowtime - wastime
    wastime = nowtime

    for i in range(0, pointCount):
        p[i].Update()

def draw():
    screen.clear()
    screen.fill(BACK_COLOR)

    for i in range(0, pointCount):
        for j in range(0, p[i].count):
            if i == pointCount - 1:
                screen.draw.line(p[i].GetPoint(j).raw_get(), p[0].GetPoint(j).raw_get(), PEN_COLOR)
            else:
                screen.draw.line(p[i].GetPoint(j).raw_get(), p[i + 1].GetPoint(j).raw_get(), PEN_COLOR)

pgzrun.go()
